<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      label-width="120px"
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormRules">
      <el-form-item label="SPU名称">
        {{ spuStore.spu.spuName }}
      </el-form-item>
      <el-form-item label="SKU 名称" prop="skuName">
        <el-input
          placeholder="SKU名称"
          v-model="skuFormData.skuName"></el-input>
      </el-form-item>

      <el-form-item label="价格(元)" prop="price">
        <el-input
          type="number"
          placeholder="请输入价格(元)"
          v-model="skuFormData.price"
          :min="0" />
      </el-form-item>

      <el-form-item label="重量(千克)" prop="weight">
        <el-input
          type="number"
          placeholder="请输入重量(千克)"
          v-model="skuFormData.weight"
          :min="0" />
      </el-form-item>

      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="规格描述"
          v-model="skuFormData.skuDesc"></el-input>
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10">
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
            class="mb-10">
            <el-form-item :label="attr.attrName">
              <el-select v-model="skuFormData.skuAttrValueList[index]">
                <el-option
                  v-for="attrValue in attr.attrValueList"
                  :key="attrValue.id"
                  :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  :label="attrValue.valueName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="mb-10">
          <el-col
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4">
            <el-form-item :label="spuSaleAttr.saleAttrName">
              <el-select v-model="skuFormData.skuSaleAttrValueList[index]">
                <el-option
                  v-for="spuAttrValue in spuSaleAttr.spuSaleAttrValueList"
                  :key="spuAttrValue.id"
                  :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuAttrValue.id}:${spuAttrValue.saleAttrValueName}`"
                  :label="spuAttrValue.saleAttrValueName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" style="width: 100px" />
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">
                默认图片
              </el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setSkuDefaultImg(row)">
                设置默认图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AddSku",
};
</script>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { useSpuStore } from "@/stores/spu";
import { useCategoryStore } from "@/stores/category";
import { getAttrListApi } from "@/api/product/attr";
import { getSpuAttrListApi, getSpuImageListApi } from "@/api/product/spu";
import { addSkuApi } from "@/api/product/sku";
import type { AttrList } from "@/api/product/model/attrModels";
import type {
  SpuSaleAttrList,
  SpuImageList,
} from "@/api/product/model/spuModel";
import type {
  SkuFormData,
  SkuImageList,
  SkuImageItem,
} from "@/api/product/model/skuModel";
const spuStore = useSpuStore();
const categoryStore = useCategoryStore();

const attrList = ref<AttrList>([]); // 平台属性
const spuSaleAttrList = ref<SpuSaleAttrList>([]); //销售属性
const spuImageList = ref<SpuImageList>([]); //图片数据

// 获取平台属性数据
onMounted(async () => {
  attrList.value = await getAttrListApi({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
});
// 获取销售属性数据
onMounted(async () => {
  spuSaleAttrList.value = await getSpuAttrListApi(spuStore.spu.id as number);
});
// 获取图片列表数据
onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(spuStore.spu.id as number);
});

const skuFormRef = ref(); // 获取表单实例
const skuFormData = reactive<SkuFormData>({
  // 定义表单数据
  skuName: "",
  skuDesc: "",
  skuDefaultImg: "",
  weight: undefined,
  price: undefined,
  skuAttrValueList: [
    // {
    //   attrId: 0,
    //   attrName: "string",
    //   id: 0,
    //   skuId: 0,
    //   valueId: 0,
    //   valueName: "string",
    // },
  ],
  skuImageList: [
    // {
    //   id: 0,
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string",
    //   skuId: 0,
    //   spuImgId: 0,
    // },
  ],

  skuSaleAttrValueList: [
    // {
    //   id: 0,
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    //   skuId: 0,
    //   spuId: 0,
    // },
  ],
});

// 自定义图片验证规则
const skuImageListValidator = (
  rule: any,
  value: SkuImageList,
  callback: any
) => {
  if (!value.length) {
    callback(new Error("请至少选中一张图片"));
    return;
  }
  if (!value.some((img) => img.isDefault)) {
    callback(new Error("选中的图片必须有默认图片"));
    return;
  }

  callback();
};

// 定义表单验证规则
const skuFormRules = reactive({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU规格描述", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  skuAttrValueList: [
    { required: true, message: "请输入SKU平台属性", trigger: "change" },
  ],
  skuSaleAttrValueList: [
    { required: true, message: "请选择SKU销售属性", trigger: "change" },
  ],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});
// 点击保存 验证表单
const submit = async () => {
  await skuFormRef.value.validate();

  await addSkuApi({
    ...skuFormData,
    category3Id: categoryStore.category3Id as number,
    spuId: spuStore.spu.id as number,
    // filter（Boolead） 可以过滤undefined 数据
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = (attr as string).split(
          ":"
        );
        return {
          attrId: +attrId,
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          attr as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
  });
  ElMessage.success("添加SKU成功");
  cancel();
};

// 勾选图片（数组）
const handleSelectionChange = (val: SkuImageList) => {
  skuFormData.skuImageList = val;
};

// 设置默认图片
const setSkuDefaultImg = (row: SkuImageItem) => {
  // 排他 0显示设置默认图片  1显示默认图片
  spuImageList.value.forEach((img) => (img.isDefault = "0"));
  // 点击的那个 设置成默认图片
  row.isDefault = "1";
  // 更新默认图片地址
  skuFormData.skuDefaultImg = row.imgUrl;

  // 判断是否选中默认图片，选中清空表单验证信息
  if (skuFormData.skuImageList.some((img) => img === row)) {
    skuFormRef.value.clearValidate(["skuImageList"]);
  }
};

// {
//   "category3Id": 0,
//   "createTime": "2022-12-24T06:40:07.458Z",
//   "id": 0,
//   "isSale": 0,
//   "price": 0,
//   "skuAttrValueList": [
//     {
//       "attrId": 0,
//       "attrName": "string",
//       "id": 0,
//       "skuId": 0,
//       "valueId": 0,
//       "valueName": "string"
//     }
//   ],
//   "skuDefaultImg": "string",
//   "skuDesc": "string",
//   "skuImageList": [
//     {
//       "id": 0,
//       "imgName": "string",
//       "imgUrl": "string",
//       "isDefault": "string",
//       "skuId": 0,
//       "spuImgId": 0
//     }
//   ],
//   "skuName": "string",
//   "skuSaleAttrValueList": [
//     {
//       "id": 0,
//       "saleAttrId": 0,
//       "saleAttrName": "string",
//       "saleAttrValueId": 0,
//       "saleAttrValueName": "string",
//       "skuId": 0,
//       "spuId": 0
//     }
//   ],
//   "spuId": 0,
//   "tmId": 0,
//   "weight": "string"
// }
const emit = defineEmits(["setIsShow"]);
// 切换组件
const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped></style>
